package server;

import server.container.Engine;
import server.mapper.Mapper;

import java.util.List;
import java.util.concurrent.*;

public class Service implements Lifecycle{

    private List<Connector> connectorList;

    private Engine engine;

    private ThreadPoolExecutor threadPoolExecutor = createThreadPoolExecutor();

    private ThreadPoolExecutor createThreadPoolExecutor(){
        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        return new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
    }

    public List<Connector> getConnectorList() {
        return connectorList;
    }

    public void setConnectorList(List<Connector> connectorList) {
        this.connectorList = connectorList;
    }

    public Engine getEngine() {
        return engine;
    }

    public void setEngine(Engine engine) {
        this.engine = engine;
    }

//    public Mapper getMapper() {
//        return mapper;
//    }
//
//    public void setMapper(Mapper mapper) {
//        this.mapper = mapper;
//    }

    public ThreadPoolExecutor getThreadPoolExecutor() {
        return threadPoolExecutor;
    }

    @Override
    public void start() {
        engine.start();
        connectorList.forEach(Connector::start);
    }
}
